/**
 * 版权所有 Copyright@@2016-03-18 1:39:12
 */
package com.fairy.sso.controller;

import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fairy.sso.annotation.FairyControllerExceptionLog;
import com.fairy.sso.cache.SSOCache;
import com.fairy.sso.config.FairyConfig;
import com.fairy.sso.core.CookieHelper;
import com.fairy.sso.core.NetHelp;
import com.fairy.sso.core.SSOConstants;
import com.fairy.sso.core.SSOHelp;
import com.fairy.sso.core.Ticket;
import com.fairy.sso.server.Factory;
import com.fairy.sso.server.SSOCacheFactory;
import com.fairy.web.common.FairyConstants;

/**
 * [TicketController.java.java]
 *
 * @Author: [yyk1504@163.com]
 * @CreateDate: [2016-03-18 1:39:12]
 * @Update: [说明本次修改内容] by [yyk1504@163.com] [2016-03-18 1:39:12]
 * @Version: [v1.0]
 */

@Controller
public class TicketController {

	private static Logger log = Logger.getLogger(TicketController.class);
	@Autowired(required=true)
	private FairyConfig fairyConfig;
	

	@RequestMapping ("/ticket.do")
	@FairyControllerExceptionLog(description="获取ticket")
	public ModelAndView ticket(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr,String token)
	{
		long start = System.currentTimeMillis();          
		log.info("=================================================同步票据=================================================");     
		ModelAndView mav = new ModelAndView(FairyConstants.JSON_VIEW_RETAIN_DEFINED_VIEW); 
		log.info("来自["+request.getContextPath()+"]的请求");
        Factory factory = new SSOCacheFactory(); 
        String cacheType=fairyConfig.getCacheType();
        SSOCache cache = factory.createSSOCache(cacheType);
        
        log.info("客户端传过来的 token is:"+token);
        
        log.info("cacheType is:"+cacheType+",cache is:"+cache.getClass().getName());
           
        Ticket t=null;
        
        String []arr=token.split(",");
        
        String tickets=arr[0];
        String ssoAppClientIp=arr[1];
        String clientIp=arr[2];
        
        //String cilentUrlList=fairyConfig.getSsoClientUrl();
    	//if(cilentUrlList.contains(ssoAppClientIp))
    	//{
            t=cache.get(tickets);
    		if(null!=t&&clientIp.equals(t.getIp()))
    		{
	    		String userId=null==t?"":t.getUserId();
    	        log.info("ticket:"+token);
    	        
    	        //userId="";
    	        String returnStr=userId+","+token;
    	        log.info("===================================返回给前端数据数据:"+returnStr+"=====================================");
    		    mav.addObject(FairyConstants.JSON_VIEW_RETAIN_DATA,returnStr);
    		}
    		else
    		{
    			if(t==null)
    			{
    				log.info("===================================返回给前端数据数据:空串,原因:t对象[票据]值为空=====================================");
    			}
    			else
    			{
    				log.info("===================================返回给前端数据数据:空串,原因:此次访问客户端ip["+ssoAppClientIp+"]与用户初次访问ip["+t.getIp()+"]=====================================");
    			}
    			
    			mav.addObject(FairyConstants.JSON_VIEW_RETAIN_DATA,"");
    		}
        /*		
    	}
    	else
    	{
    		log.info("===================================返回给前端数据数据:空串,原因:客户端ip["+ssoAppClientIp+"]不受信任=====================================");
    		mav.addObject(FairyConstants.JSON_VIEW_RETAIN_DATA,"");
    	}
    	*/
        long end = System.currentTimeMillis();        
        log.info("<<===================================同步ticket  运行时间:"+(end-start)+"毫秒==========================================>>");     
        log.info("=================================================同步票据=================================================");     
        return mav;
	}

	@RequestMapping ("/createTicket.do")
	@FairyControllerExceptionLog(description="客户端请求创建ticket")
	public ModelAndView createTicket(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr,String token)
	{
		long start = System.currentTimeMillis();          
        
		ModelAndView mav = new ModelAndView(FairyConstants.JSON_VIEW_RETAIN_DEFINED_VIEW); 
		 String ticketKey=null;
		try{
			log.info("来自["+request.getContextPath()+"]的请求");
	        Factory factory = new SSOCacheFactory(); 
	        String cacheType=fairyConfig.getCacheType();
	        SSOCache cache = factory.createSSOCache(cacheType);
	        
	        log.info("客户端传过来的 token is:"+token);
	        
	        log.info("cacheType is:"+cacheType+",cache is:"+cache.getClass().getName());
	           
	        String []arr=token.split(",");
	        
	        String userId=arr[0];
	        String clientIp=arr[1];
	       
	        
	        //String ticketSecretkey=fairyConfig.getSsoTicketSecretkey();

	        ticketKey=SSOHelp.getMD5TicketKey();
	        //String clusterIp=fairyConfig.getSsoClientUrl();
	        InetAddress netAddress = NetHelp.getInetAddress();  
            String localHostIp=NetHelp.getHostIp(netAddress);
	        
	        Ticket ticket=SSOHelp.getTicket("ssoServer",localHostIp,userId, userId, clientIp, ticketKey);
	                
	        cache.set(ticketKey, ticket);
	        log.info("从缓存取ticket:"+cache.get(ticketKey).toString());
	        
	        long end = System.currentTimeMillis();        
	        log.info("<<===================同步ticket  运行时间:"+(end-start)+"毫秒============================>>");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		mav.addObject(FairyConstants.JSON_VIEW_RETAIN_DATA,ticketKey);
	    return mav;
	}
	
	
	@RequestMapping ("/createCookie.do")
	@FairyControllerExceptionLog(description="客户端请求创建cookie")
	public ModelAndView createCookie(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr,String ticket)
	{
		long start = System.currentTimeMillis();          
        
		ModelAndView mav = new ModelAndView(FairyConstants.JSON_VIEW_RETAIN_DEFINED_VIEW); 

		String code="111111";
		String msg="fail";
		try{
			String ssoCookie=request.getParameter(SSOConstants.TICKET);
			System.out.println(this.getClass().getName()+",:::::::::::::::::::ssoCookie:"+ssoCookie);
			log.info(this.getClass().getName()+",:::::::::::::::::::ssoCookie:"+ssoCookie);

	        	if(null!=ssoCookie)
	        	{
	    			String domain=  NetHelp.getDomainOrIP(request);//NetHelp.getDomain(request);
	        		System.out.println(this.getClass().getName()+"-------------------domain-------------------------"+domain);
	        		log.info(this.getClass().getName()+"-------------------domain-------------------------"+domain);

            		boolean isIp=NetHelp.isIP(domain);
            		if(!isIp)
            		{
                		System.out.println("<-------------------   domain is not ip"+domain+"------------------------->");
                		log.info("<-------------------   domain is not ip"+domain+"------------------------->");
            			domain="."+domain;
            		}
            		else
            		{
            	        //本机ip
            			InetAddress addr = InetAddress.getLocalHost();
            	        String ssoAppClientIp=addr.getHostAddress().toString();//获得本机IP
            	        
            	        
	        			System.out.println("<=====================================netpay 配置为130时1.1.0版本获得的 本机ip:::::::"+ssoAppClientIp+"=====================================>");
	        			log.info("<=====================================netpay 配置为130时1.1.0版本获得的本机ip:::::::"+ssoAppClientIp+"=====================================>");
	        			ssoAppClientIp=NetHelp.getLocalHostIp();
	        	 
	        			System.out.println("<=====================================netpay 配置为130时1.1.1版本获得的 本机ip:::::::"+ssoAppClientIp+"=====================================>");
	        			log.info("<=====================================netpay 配置为130时1.1.1版本获得的 本机ip:::::::"+ssoAppClientIp+"=====================================>");
	        			
	        	                    	        
            			domain=ssoAppClientIp;
                		System.out.println("<-------------------   domain is  ip"+domain+"------------------------->");
                		log.info("<-------------------   domain is  ip"+domain+"------------------------->");
            		}
                	
       			    //创建cookie
        			CookieHelper.addCookie(response, domain, "/", SSOConstants.SSO_COOKIE_KEY,ssoCookie, -1);
        			code="000000";
        			msg="successful";
            		System.out.println(this.getClass().getName()+"<++++++++++++++++++++++++++++++++++"+domain+"   设置cookie成功++++++++++++++++++++++++++++++++++++>");
            		log.info(this.getClass().getName()+"<++++++++++++++++++++++++++++++++++"+domain+"   设置cookie成功++++++++++++++++++++++++++++++++++++>");	
	        	}


		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
        long end = System.currentTimeMillis();        
        log.info("<<===================运行时间:"+(end-start)+"毫秒============================>>");
		String json=
				"{"
				+ "\"ssoMsg\":\""+msg+"\","
				+ "\"ssoCode\":\""+code+"\""
				+ "}";
		mav.addObject(FairyConstants.JSON_VIEW_RETAIN_DATA,json);
	    return mav;
	}
}
